package com.example.googlemapdrawroutelast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MenuActivity extends ActionBarActivity implements OnClickListener {

	private Button buttonAddRoute;
	private Button buttonViewRoutes;
	private ApplicationData appData;
	//
	private ProgressBar progressBar;

	ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);
		Bundle extras = getIntent().getExtras();
		this.appData = new ApplicationData();
		if (extras != null) {
			int idUser = extras.getInt("idUser");
			if (idUser != 0) {
				this.appData.setIdUser(idUser);
			}
		}
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);

		this.initialise();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);

		// TextView txtView = (TextView) findViewById(R.id.tvMessage);
		// txtView.setText(idUser);
		return true;
	}

	private void initialise() {

		buttonAddRoute = (Button) findViewById(R.id.buttonCreateRoute);
		buttonViewRoutes = (Button) findViewById(R.id.buttonViewRoute);

		buttonAddRoute.setOnClickListener(this);
		buttonViewRoutes.setOnClickListener(this);

	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.buttonCreateRoute:
			createNewActivitywithMap(v);
			break;
		case R.id.buttonViewRoute:
			new GetRoutesTask(v).execute();
			break;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void createNewActivitywithMap(View v) {
		
		int iduseros  = appData.getIdUser();
		Intent intent = new Intent(v.getContext(), MainActivity.class);
		intent.putExtra("idUser", iduseros); // Optional
		intent.putExtra("isRouteDrawing", true);
																// parameters
		startActivityForResult(intent, 0);
	}

	private class GetRoutesTask extends AsyncTask<Void, Void, Boolean> {

		private View view;

		public GetRoutesTask(View view) {
			super();
			this.view = view;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			progressBar.setVisibility( ProgressBar.VISIBLE);
			//Toast.makeText(getBaseContext(), "Logowanie...", Toast.LENGTH_LONG).show();
			
		}
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				String strUrl = "http://" + UrlClass.getUrl() + "/v1/routes";
				URL url = new URL(strUrl);
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setConnectTimeout(15000);
				connection.setReadTimeout(15000);
				connection.setRequestMethod("GET");
				connection.setDoOutput(true);

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();
				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				iStream.close();

				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);
				JSONArray routesArray = jsonResponse.getJSONArray("routes");

				routes.clear();

				for (int i = 0; i < routesArray.length(); i++) {
					JSONObject route = (JSONObject) routesArray.get(i);
					routes.add(new RouteInfo(
							 route.getInt("id_route"),
							 route.getString("name_route"),
							 route.getString("description"),
							 null,
							 null,
							 route.getInt("id_user")));
				}
				

			} catch (Exception e) {
				Toast.makeText(getBaseContext(), e.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			createNewListOfRouteActivity(view);
		}

		private void createNewListOfRouteActivity(View v) {

			Intent intent = new Intent(v.getContext(),
					ListOfRoutesActivity.class);
			intent.putParcelableArrayListExtra("routes", routes);
			
			int iduseros  = appData.getIdUser();
			intent.putExtra("idUser", iduseros);
			progressBar.setVisibility( ProgressBar.INVISIBLE);
			startActivityForResult(intent, 0);
			
			
		}

	}
}
